package com.wk.springboot.ttl.context;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

public class Application {

    public static ThreadLocal threadLocal = new ThreadLocal();

    public static InheritableThreadLocal inheritableThreadLocal = new InheritableThreadLocal();

    public static void main(String[] args) {

        //模拟web应用中为每个请求设置唯一的请求ID
        String requestId = "REQ-" + System.nanoTime();
        RequestContext.setRequestId(requestId);
        threadLocal.set(requestId);
        inheritableThreadLocal.set(requestId);
        try {
            ExecutorService executorService = ThreadPoolUtil.getExecutorService();
            ExecutorService executorService1 = Executors.newFixedThreadPool(1);
            IntStream.range(0, 5).forEach(i -> {
                executorService1.submit(() -> {
                    System.out.println("task" + i + "running tName"
                            + Thread.currentThread().getName() + " task ttl RequestContext"
                            + RequestContext.getRequestId() +
                            "   threadLocal reqId" + threadLocal.get() + " inheritableThreadLocal"
                            + inheritableThreadLocal.get());
                    inheritableThreadLocal.set(inheritableThreadLocal.get() + "random" + i);
                    RequestContext.setRequestId(RequestContext.getRequestId() + "random" + i);
                });
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
//            IntStream.range(0, 5).forEach(i -> {
//                executorService.submit(() -> {
//                    System.out.println("task" + i + "running tName"
//                            + Thread.currentThread().getName() + " task ttl reqId"
//                            + RequestContext.getRequestId() +
//                            "threadLocal reqId" + threadLocal.get()+" inheritableThreadLocal"
//                            + inheritableThreadLocal.get());
//                });
//            });
        } finally {
            RequestContext.clear();
            threadLocal.remove();
            inheritableThreadLocal.remove();
        }
    }
}